import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue'

export const useUserStore = defineStore('user', () => {
   /* 清理数据 */
   const ClearStorage = async() => {
    sid.value = ''
    uid.value = 0
    sessionStorage.clear()
    localStorage.clear()
  }
  
  const sid = ref(window.localStorage.getItem('sid') || '')
  const uid = ref(window.localStorage.getItem('uid') || 0)
  
  const setSid = (val) => {
    sid.value = val
  }

  //监听sid变化,并保存本地
  watch(() => sid.value, () => {
    window.localStorage.setItem('sid', sid.value)
  })

  const setUid = (val) => {
    uid.value = val
  }

  //监听sid变化,并保存本地
  watch(() => uid.value, () => {
    window.localStorage.setItem('uid', uid.value)
  })

  const userInfo = ref({})
  try {
    if (window.localStorage.getItem('user_info')){
      userInfo.value = JSON.parse(window.localStorage.getItem('user_info'))
    }
  }catch (e) {}
  console.log("wyq", "用户信息：", userInfo.value)

  watch(() => userInfo.value, () => {
    window.localStorage.setItem('user_info', JSON.stringify(userInfo.value))
  })

  const setUserInfo = (val) => {
    console.log("wyq", "设置用户信息：", val)
    userInfo.value = val
  }


  const sideMode = ref('dark')

  const baseColor = computed(() => {
    if (sideMode.value === 'dark') {
      return '#fff'
    } else if (sideMode.value === 'light') {
      return '#191a23'
    } else {
      return sideMode.value
    }
  })

  const backgroundColor = computed(() => {
    if (sideMode.value === 'dark') {
      return '#191a23'
    } else if (sideMode.value === 'light') {
      return '#fff'
    } else {
      return sideMode.value
    }
  })

  return {
    ClearStorage,
    setSid,
    sid,
    setUid,
    uid,
    setUserInfo,
    userInfo,
    sideMode,
    baseColor,
    backgroundColor
  }
})